﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace Talk
{
    public partial class register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] != null)
            {
                Response.Redirect("/index.aspx");
            }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            try
            {
                errormsg.Text = "";
                if (passcheck.Text != password.Text)
                {
                    errormsg.Text = "两次密码输入不同！";
                    return;
                }
                if(username.Text.Length > 12)
                {
                    errormsg.Text = "用户名太长！";
                    return;
                }
                if (username.Text.Length < 3)
                {
                    errormsg.Text = "用户名太短！";
                    return;
                }
                Regex r = new Regex("[^a-zA-Z0-9]");
                if(r.IsMatch(username.Text))
                {
                    errormsg.Text = "用户名中含有非法字符！";
                    return;
                }
                SHA1 sha1 = SHA1.Create();
                byte[] shares = sha1.ComputeHash(System.Text.Encoding.Default.GetBytes(password.Text));
                string passsha1 = BitConverter.ToString(shares, 7, 7);
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["talkconn"].ConnectionString);
                conn.Open();
                string sql = "insert into Users(Username, Password) values('"
                    + username.Text + "', '" + passsha1 + "')";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();
                // TODO : 添加记录数据到Log表
                cmd.CommandText = "insert into Actions(What,Time,IP) values("
                   + "'" + username.Text + "注册','"
                   + DateTime.Now.ToString() + "','"
                   + Request.UserHostAddress.ToString()
                   + "');";
                cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (System.Exception ex)
            {
                errormsg.Text = ex.Message;
            }
        }
    }
}
